package com.lq.javawebTest.controller;

import com.lq.JDBC.entity.User;
import com.lq.javawebTest.core.*;
import com.lq.javawebTest.core.entity.HttpRequest;
import com.lq.javawebTest.core.entity.HttpResponse;
import com.lq.javawebTest.core.entity.Session;
import com.lq.javawebTest.core.inter.Servlet;

public class IndexServlet implements Servlet {
    @Override
    public void service(HttpRequest request, HttpResponse response) {
        if(request.getHeader("Cookie")!=null){
            //从给他分配的cookie中获取id,并设置响应的session
            String cookie = request.getHeader("Cookie");
            String sessionId = cookie.split("=")[1];
            Session session = Container.getSession(sessionId);
            if(session == null || session.get("user")==null){
                HttpResponse.redirect(response,"http://localhost:8080/login.html");
                return;
            }
            //注意，我们容器中的session就是一个继承了hashmap的类其类型为<String,object>,在LoginServlet中我们往container的session中写入的是“user",user
            //所以这里我们为例得到user实例，就需要传入”user"这个String字符串拿到这个响应的user实例映射
            User user = (User)session.getAttribute("user");
            HttpResponse.success(response, "当前用户："+user.getUsername());
        }else{
            //如果没有cookie，就重定向页面到登陆页面
            HttpResponse.redirect(response,"http://localhost:8080/login.html");
        }
    }
}
